jetcrab\ast\common/
position.rs1use crate::vm::types::{ColumnNumber, LineNumber, SourcePosition};
2use serde::{Deserialize, Serialize};
3use std::fmt;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
6pub struct Position {
7 pub line: LineNumber,
8 pub column: ColumnNumber,
9}
10
11impl Position {
12 pub fn new(line: usize, column: usize) -> Self {
13 Self {
14 line: LineNumber::new(line),
15 column: ColumnNumber::new(column),
16 }
17 }
18
19 pub fn new_typed(line: LineNumber, column: ColumnNumber) -> Self {
20 Self { line, column }
21 }
22
23 pub fn from_source_position(pos: SourcePosition) -> Self {
24 Self {
25 line: pos.line,
26 column: pos.column,
27 }
28 }
29
30 pub fn to_source_position(&self) -> SourcePosition {
31 SourcePosition {
32 line: self.line,
33 column: self.column,
34 }
35 }
36}
37
38impl Default for Position {
39 fn default() -> Self {
40 Position {
41 line: LineNumber::new(1),
42 column: ColumnNumber::new(1),
43 }
44 }
45}
46
47impl fmt::Display for Position {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(f, "{}:{}", self.line, self.column)
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct Span {
55 pub start: Position,
56 pub end: Position,
57}
58
59impl Span {
60 pub fn new(start: Position, end: Position) -> Self {
61 Self { start, end }
62 }
63
64 pub fn from_positions(
65 start_line: usize,
66 start_col: usize,
67 end_line: usize,
68 end_col: usize,
69 ) -> Self {
70 Self {
71 start: Position::new(start_line, start_col),
72 end: Position::new(end_line, end_col),
73 }
74 }
75
76 pub fn from_positions_typed(
77 start_line: LineNumber,
78 start_col: ColumnNumber,
79 end_line: LineNumber,
80 end_col: ColumnNumber,
81 ) -> Self {
82 Self {
83 start: Position::new_typed(start_line, start_col),
84 end: Position::new_typed(end_line, end_col),
85 }
86 }
87}